from django.conf import settings
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from app03.models import Color,Cate,Goods,Version
from app03.serializer import CateSER,ColorSER,GoodsSER,VersionSER,GoodsShowSER


import redis
from itsdangerous import TimedJSONWebSignatureSerializer
# Create your views here.

# 反序列化用户使用
token_ser = TimedJSONWebSignatureSerializer(settings.SECRET_KEY,86400)

# 连接redis
r = redis.Redis(host='127.0.0.1',port='6379',db=8)

class CateView(APIView):
    def post(self,request):
        cate_id = request.data.get('cate_id')  # 代表上级分类 0 ，表示顶级分类
        cate_name = request.data.get('cate_name')

        # 从数据库获取分类对象 ，用于判断分类是否存在
        # filter获取到内容以后以列表形式返回，如果获取不到，返回空列表：None值，

        cate_obj = Cate.objects.filter(cate_name=cate_name)

        # 判断是不是顶级分类
        if cate_id == '0':
            if cate_obj:
                return Response({'msg':'分类已存在','code':400})
            else:
                data = {'cate_name':cate_name}

                # 反序列化添加
                cate_ser = CateSER(data=data)
                # 进行数据验证
                if cate_ser.is_valid():
                    cate_ser.save()
                    return Response({'msg':'添加分类成功','code':200})
                else:
                    return Response({'error':cate_ser.errors})
        else:
            if cate_obj:
                return Response({'msg': '分类已存在', 'code': 400})
            else:
                data = {'cate_name': cate_name,'cid':cate_id}

                # 反序列化添加
                cate_ser = CateSER(data=data)
                # 进行数据验证
                if cate_ser.is_valid():
                    cate_ser.save()
                    return Response({'msg': '添加分类成功', 'code': 200})
                else:
                    return Response({'error': cate_ser.errors})
    def get(self,request):
        cate_list = Cate.objects.all()

        cate_serializer = CateSER(cate_list,many=True)
        # 返回数据
        return Response(cate_serializer.data)
    def put(self,request):
        cate_id  = request.data.get('cate_id')
        cate_name = request.data.get('cate_name')

        # 通过分类id来获取分类对象
        cate_obj = Cate.objects.filter(pk=cate_id).first()
        # 判断分类是否存在
        if cate_obj:
            data = {
                'cate_name':cate_name
            }
            # instance 要修改的对象 ，data 要修改的数据
            cate_serializers = CateSER(instance=cate_obj,data=data)
            if cate_serializers.is_valid():
                cate_serializers.save()
                return Response({'msg':'OK','code':200})
            else:
                return Response({'msg':'修改失败','code':400})
        else:
            return Response({'msg':'分类不存在','code':400})
    def delete(self,request):
        cate_id = request.GET.get('cate_id')
        cate_obj = Cate.objects.filter(pk=cate_id)
        cate_obj.delete()
        return Response({'msg':'OK'})



# 颜色
class ColorView(APIView):
    def post(self,request):
        color = request.data.get('color_name')
        color_obj = Color.objects.filter(color_name=color)
        if color_obj:
            return Response({'msg':'颜色已存在','code':400})
        else:
            color_serializers = ColorSER(data=request.data)
            if color_serializers.is_valid():
                color_serializers.save()
                return Response({'msg':'添加颜色成功','code':200})
            else:
                return Response({'error':color_serializers.errors})
    def get(self,request):
        colores = Color.objects.all()

        color_ser  = ColorSER(colores,many=True)
        return  Response({color_ser.data})
# 版本
class VersionView(APIView):
    def post(self,request):
        version = request.data.get('version_name')
        version_obj = Version.objects.filter(color_name=version)
        if version_obj:
            return Response({'msg':'版本已存在','code':400})
        else:
            version_serializers = ColorSER(data=request.data)
            if version_serializers.is_valid():
                version_serializers.save()
                return Response({'msg':'添加颜色成功','code':200})
            else:
                return Response({'error':version_serializers.errors})
    def get(self,request):
        versiones = Version.objects.all()

        version_ser  = VersionSER(versiones,many=True)
        return  Response({version_ser.data})
# 商品表
class GoodsView(APIView):
    def post(self,request):
        """
        [1,3,5]
        """
        goods_name = request.data.get('goods_name')
        goods_price = request.data.get('goods_price')
        color = request.data.get('color')
        color_list = [i for i in color if i != ',']
        version = request.data.get('version')
        version_list= [x for x in version if x != ',']
        detail = request.data.get('detail')
        spen = request.data.get('spen')
        goods_img = request.data.get('goods_img')

        # 获取数据库中的商品对象，用于判断商品是否存在
        goods_obj = Goods.objects.filter(goods_name=goods_name)
        # 判断商品是否存在
        if goods_obj:
            # 条件成立，商品存在，直接返回
            return Response({'msg':'商品已存在','code':400})
        data = {'goods_name':goods_name,'goods_price':goods_price,'goods_img':goods_img,'color':color_list,'version':version_list,
                'detail':detail,'spen':spen}
        goods_serializer = GoodsSER(data=data)
        # 验证数据
        if goods_serializer.is_valid():
            goods_serializer.save()
            return Response({'msg':'添加商品成功','code':200})
        else:
            return Response({'error':goods_serializer.errors})

    def get(self,request):
        goods = Goods.objects.all()

        goods_ser = GoodsSER(goods,many=True)

        return Response(goods_ser.data)
    def delete(self,request):
        goods_id = request.GET.get('goods_id')

        goods_obj = Goods.objects.filter(pk=goods_id)

        goods_obj.delete()
        return Response({'msg':'删除成功','code':200})
    def put(self,request):
        goods_id = request.data.get('goods_id')
        goods_name = request.data.get('goods_name')
        goods_price = request.data.get('goods_price')
        color = request.data.get('color')
        color_list = [i for i in color if i != ',']
        version = request.data.get('version')
        version_list= [x for x in version if x != ',']
        detail = request.data.get('detail')
        spen = request.data.get('spen')
        goods_img = request.data.get('goods_img')

        goods_obj = Goods.objects.filter(pk=goods_id).first()
        if goods_obj:
            data = {
                'goods_name': goods_name, 'goods_price': goods_price, 'goods_img': goods_img, 'color': color_list,
                'version': version_list,
                'detail': detail, 'spen': spen
            }
            goods_ser = GoodsSER(instance=goods_obj,data=data)
            if goods_ser.is_valid():
                goods_ser.save()
                return Response({'msg':'修改成功','code':200})
            else:
                return Response({'error':goods_ser.errors})
        else:
            return Response({'msg':'修改失败','code':400})

class GoodsShowView(APIView):
    def get(self,request):
        cate_id = request.GET.get('cate_id')
        goods_list = Goods.objects.filter(cate=cate_id)

        goods_ser = GoodsShowSER(goods_list,many=True)

        return Response(goods_ser.data)



class DetailView(APIView):
    def get(self,request,goods_id):
        goods_info = Goods.objects.filter(pk=goods_id).first()
        if goods_info:
            goods_ser = GoodsShowSER(goods_info)
            print(goods_ser.data)
            return Response(goods_ser.data)
        else:
            return Response({'msg':'失败'})

class AddCartView(APIView):
    def post(self,request):
        """
        reids 哈希 用户id做主键：{'1':2,'2':3}
        """
        # 获取前端提交数据
        token = request.data.get('token')
        goods_id = request.data.get('goods_id')
        color_id  = request.data.get('color_id')
        goods_num = request.data.get('goods_num')
        # 反序列化用户信息
        user_id = token_ser.loads(token).get('user_id')
        # 拼接key
        # goods_info = '{}{}{}'.format(goods_id,color_id,version_id)

        r.hincrby(user_id,goods_id,goods_num)
        return Response({'msg':'添加成功','code':200})

class ShowCartView(APIView):
    def get(self,request):
        token = request.GET.get('token')
        user_id = token_ser.loads(token).get('user_id')
        keys_info = r.hgetall(user_id)
        goods_Data = []
        for k,v in keys_info.items():
            goods_obj =Goods.objects.get(pk=k.decode()[0])
            print(goods_obj)
            goods_Data.append({
                'id':goods_obj.pk,
                'goods_name':goods_obj.goods_name,
                'goods_price':str(goods_obj.goods_price),
                'color':[{'id':i.pk,'color_name':i.color_name} for i in goods_obj.color.filter(pk=k.decode()[0])],

                'goods_img':goods_obj.goods_img.url,
                'goods_num':v.decode()
            })
            print(goods_Data)
        return Response({'data':goods_Data})

 # 购物车增加数量
class AddNumView(APIView):
    def post(self,request):
        # 获取前端提交的数据
        token = request.data.get('token')
        # 反序列化用户信息，并提取用户id
        user_id = token_ser.loads(token).get('user_id')
        goods_id = request.data.get('goods_id')
        # 前端点击加号,每次累计加1
        r.hincrby(user_id,goods_id,1)
        return Response({'msg':'OK','code':200})

# 购物车减少数量
class MinNumView(APIView):
    def post(self,request):
        token = request.data.get('token')
        user_id = token_ser.loads(token).get('user_id')
        goods_id = request.data.get('goods_id')
        # 数量累计减
        if int(r.hget(user_id,goods_id).decode()) > 1:
            r.hincrby(user_id,goods_id,-1)
            return Response({'msg':'OK','code':200})
        else:
            return Response({'msg':'数量最小为1，不能再减了'})


# 删除购物车商品
class DeleteCartView(APIView):
    def post(self,request):
        token = request.data.get('token')
        user_id = token_ser.loads(token).get('user_id')
        goods_id = request.data.get('goods_id')

        # 拿到用户id和商品id，然后删除redis哈希内的key
        r.hdel(user_id,goods_id)
        return Response({'msg':'删除成功','code':200})